package com.singfan.common.db;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import com.singfan.common.SingFanException;
import com.singfan.common.db.config.MonitorLog;

import java.io.IOException;

/**
 * 数据库相关的日志工具类
 * Author: HanSongHe
 * Date: 15-7-25 下午6:20
 */
public class DbLogger {
    private static MonitorLog monitorLog;
    private static Logger executeSqlLogger;
    private static Logger executeSqlErrorLogger;

    /**
     * 初始化日志工具类
     */
    public static void init(){
        try {
            monitorLog = DbContext.getDbConfigProvider().getMonitorLog();
            executeSqlLogger = createLogger("ExecuteSqlLogger", monitorLog.getTraceFile());
            executeSqlErrorLogger = createLogger("ExecuteSqlErrorLogger", monitorLog.getErrorFile());
        }
        catch (Exception e) {
            throw new SingFanException(String.format("DbLogger.init() error: %s !", e.getMessage()), e);
        }
    }

    /**
     * 执行sql的log信息
     * @param usedTime 使用时间
     * @param hashKey 分表的key
     * @param sql 执行的sql
     * @param params sql的参数
     */
    public static void executeSqlLog(long usedTime, Object hashKey, String sql, String params){
        String log = String.format("%1$d|%2$s|%3$s|%4$s", usedTime, hashKey, sql, params);
        if(monitorLog.isOnlyWarning()){
            if(usedTime >= monitorLog.getWarningTime()){
                executeSqlLogger.info(log);
            }
        }
        else{
            executeSqlLogger.info(log);
        }
    }

    /**
     * 执行sql时出错的log信息
     * @param hashKey 分表的key
     * @param sql 执行的sql
     * @param params sql的参数
     * @param e 出错信息
     */
    public static void executeSqlErrorLog(Object hashKey, String sql, String params, Exception e){
        String log = String.format("%1$s|%2$s|%3$s|%4$s", hashKey, sql, params, e.getMessage());
        executeSqlErrorLogger.info(log);
    }

    private static Logger createLogger(String loggerName, String fileName) throws IOException {
        Logger logger = Logger.getLogger(loggerName);
        logger.setAdditivity(false);
        logger.setLevel(Level.INFO);
        //构造函数一定要用这个有参数的，否则会抛出找不到DailyRollingFileAppender的OutputStream异常
        DailyRollingFileAppender dailyRollingFileAppender = new DailyRollingFileAppender(new PatternLayout("%d|%m%n"), fileName, "'.'yyyyMMdd");
        dailyRollingFileAppender.setName(loggerName + "_Appender");

        logger.addAppender(dailyRollingFileAppender);

        return logger;
    }
}
